package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.User;
import com.weilai.service.BackgroundService;
import com.weilai.service.CaptchaService;
import com.weilai.service.EmailService;
import com.weilai.service.UserService;
import com.weilai.service.serviceImpl.EmailServiceImpl;
import com.weilai.service.serviceImpl.UserServiceImpl;

import com.weilai.util.PasswordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Random;

@Api(tags = "注册", description = "提供注册方法的接口")
@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;
    @Autowired
    private BackgroundService backgroundService;

    @ApiOperation(value = "注册方法", notes = "注册方法，需要输入用户邮箱、验证码、密码、用户名")
    @ApiResponses({
            @ApiResponse(code = 200, message = "注册成功")
    })
    //注册
    @PostMapping
    public ModelAndView register(@RequestParam String email,
                                 @RequestParam String code,
                                 @RequestParam String password,
                                 @RequestParam String username,
                                 HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("registerEmail", "");
        session.setAttribute("registerPassword", "");
        session.setAttribute("registerUsername", "");
        session.setAttribute("registerCode", "");
        try {

            ModelAndView mav = new ModelAndView();
            User user = userService.getUserByEmail(email);

            // 检查邮箱是否已注册
            if (user != null) {
                throw new BusinessException(Code.PROJECT_DATA_DUPLICATE, "该邮箱已有账户，请登录");
            }

            // 名字复杂度检验
            if (username.length() < 2 || username.length() > 8) {
                session.setAttribute("registerEmail", email);
                session.setAttribute("registerPassword", password);
                session.setAttribute("registerCode", code);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "用户名长度应在2-8个字符之间");
            }

            // 名字唯一性检验
            if (userService.getUserByUsername(username) != null) {
                session.setAttribute("registerEmail", email);
                session.setAttribute("registerPassword", password);
                session.setAttribute("registerCode", code);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "用户名重复，请重新输入");
            }

            // 验证码校验
            if (captchaService.getByEamil(email)==null || !code.equals(String.valueOf(captchaService.getByEamil(email).getCaptchaCode()))) {
                session.setAttribute("registerEmail", email);
                session.setAttribute("registerPassword", password);
                session.setAttribute("registerUsername", username);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "验证码错误，请重试");
            }

            // 密码复杂度校验
            if (password.length() < 6 || password.length() > 20) {
                session.setAttribute("registerEmail", email);
                session.setAttribute("registerUsername", username);
                session.setAttribute("registerCode", code);
                session.setAttribute("registerPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码长度需在6-20位之间");
            }

            boolean hasLetter = password.chars().anyMatch(Character::isLetter);
            if (!hasLetter) {
                session.setAttribute("registerEmail", email);
                session.setAttribute("registerUsername", username);
                session.setAttribute("registerCode", code);
                session.setAttribute("registerPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码必须包含字母");
            }

            // 创建用户
            User newUser = new User();
//            newUser.setPassword(PasswordUtil.encode(password));
            newUser.setPassword(password);
            newUser.setUsername(username);
            newUser.setEmail(email);
            newUser.setCreatedAt(LocalDateTime.now());
            newUser.setUpdatedAt(LocalDateTime.now());

            try {
                userService.insertUser(newUser);
            } catch (Exception e) {
                session.setAttribute("registerEmail", email);
                session.setAttribute("registerUsername", username);
                session.setAttribute("registerCode", code);
                session.setAttribute("registerPassword", password);
                throw new SystemException(Code.SYSTEM_DB_ERROR, "用户注册失败，请稍后重试", e);
            }

            user = userService.getUserByEmail(email);
            session.setAttribute("userId", user.getId());
            user.setPassword("****");
            session.setAttribute("user", user);
            //注册成功后添加默认背景
            backgroundService.insertBackground(user.getId(),"https://haven-file.oss-cn-beijing.aliyuncs.com/%E8%83%8C%E6%99%AF.png");

            mav.setViewName("redirect:/mainPageRecommend");

            session.removeAttribute("registerPassword");
            session.removeAttribute("registerEmail");
            session.removeAttribute("registerUsername");
            session.removeAttribute("registerCode");

            return mav;
        } catch (BusinessException e) {
            session.setAttribute("registerEmail", email);
            session.setAttribute("registerUsername", username);
            session.setAttribute("registerCode", code);
            session.setAttribute("registerPassword", password);
            throw e; // 业务异常直接抛出
        } catch (Exception e) {
            session.setAttribute("registerEmail", email);
            session.setAttribute("registerUsername", username);
            session.setAttribute("registerCode", code);
            session.setAttribute("registerPassword", password);
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "注册过程中出现系统错误", e);
        }
    }

    @ApiOperation(value = "发送验证码方法", notes = "发送验证码，需要输入用户邮箱")
    @ApiResponses({
            @ApiResponse(code = 200, message = "发送成功")
    })
    //发送验证码
    @PostMapping("/sendCode")
    public ModelAndView sendCode(@RequestParam String email,
                                 HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("registerEmail", "");

        try {
            ModelAndView mav = new ModelAndView();

            //发送验证码
            captchaService.sendCode(email);

            mav.addObject("result", "验证码发送成功");
            mav.setViewName("register");
            session.removeAttribute("registerEmail");
            return mav;
        } catch (BusinessException e) {
            session.setAttribute("registerEmail", email);
            throw e;
        } catch (Exception e) {
            session.setAttribute("registerEmail", email);
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "发送验证码过程中出现系统错误", e);
        }
    }
}
